<?php

namespace app\zyhsapi\model;


use app\common\lib\Util;
use app\zyhsapi\model\comment\ZyhsArticleComment;
use app\zyhsapi\model\comment\ZyhsArticleGood;
use XznsTools\cache\zyhs\CacheManageZyhs;

class ZyhsPxyzUserQuestion extends BaseCacheZyhs
{
    protected $table = 'good_wechat.zyhs_pxyz_user_question';

    protected $cacheModel = 'zyhs.pxyz_question';

    protected $totalNum = 0;
    protected $isDelUserReadQuestionRecord = false;

    /**
     * 发布 平行宇宙 内容
     * @param int $uid
     * @param array $data
     * @return int
     */
    public function SaveData(int $uid, array $data): int
    {
        try
        {
            if (isset($data['imgs']) && is_array($data['imgs']))
            {
                $data['imgs'] = json_encode($data['imgs'], JSON_UNESCAPED_UNICODE);
            }
            if (isset($data['recode_data']) && is_array($data['recode_data']))
            {
                $data['recode_data'] = json_encode($data['recode_data'], JSON_UNESCAPED_UNICODE);
            }
            $id = $this->insertGetId($data);
            $id = (int)$id;
            // 添加至 平行宇宙 - 我的发布列表
            $this->listDataAdd($uid, [$id => $data['create_time']]);
            // 添加 时间 排序
            CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel)->listAdd([$id => $data['create_time']], 0, 'time_sort');
            // 添加至推荐值排序列表
            CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel)->listAdd([$id => 0], 0, 'recommended_sort');

            return $id;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);

            return 0;
        }
    }

    public function delData(int $id, int $uid, bool $isTop = false, bool $isRecommend = false)
    {
        try
        {
            $this->where(['id' => $id])->update(['status' => 0]);
            CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $id)->rmCache();
            // 我的发布 列表删除
            $this->listDataDel($uid, [$id]);
            if ($isTop)
            {   // 后台强制置顶
                CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel)->rmCache('admin_recommended_top');
            }
            if ($isRecommend)
            {   // 后台推荐
                CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel)->delJudge($id, 'admin_recommended');
            }
            // 删除 广场 时间排序
            CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel)->delJudge($id, 'time_sort');
            // 删除 广场 推荐值排序
            CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel)->delJudge($id, 'recommended_sort');

            return true;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return false;
        }
    }

    /**
     * 获取 首页 推荐问答列表
     * @param int $uid
     * @param int $page
     * @param int $limit
     * @return array
     * @throws \Exception
     */
    public function getRecommentQids(int $uid, int $page, $limit = 10)
    {
        $nowTime = time();
        $resIds = [];
        $excludeIds = [];
        if ($uid)
        {   // 获取 用户 最新发布的一条
            request()->get(['page' => 1]);
            $this->pageLimit = 2;
            $pageData = $this->getListPage($uid, 'create_time', ['create_time', 'status', 'id'], 0, 'desc', 0);
            foreach ($pageData['data'] as $itemInfo)
            {
                if ($nowTime - $itemInfo['create_time'] < 86400 && (int)$itemInfo['status'] === 1)
                {
                    $excludeIds[] = $itemInfo['id'];
                    break;
                }
            }
        }
        // 获取后台强制置顶
        $topId = CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel)->setCacheType('string')->getDataAndSet(function ()
        {
            try
            {
                $id = $this->where(['is_top' => 1, 'is_hide' => 0, 'status' => 1])->value('id');
                return $id ?: '-999';
            }
            catch (\Exception $e)
            {
                return '';
            }
        }, [], 'admin_recommended_top');

        if ($topId && $topId !== '-999')
        {
            $excludeIds[] = $topId;
        }

        if ($page === 1)
        {
            $resIds = $excludeIds;
        }
        $ids = $this->getAdminRecommentQids($uid, 2, $excludeIds);
        $resIds = array_merge($resIds, $ids);
        $excludeIds = array_merge($excludeIds, $ids);
        $oldRecommentIds = [];
        if ($uid)
        {
            // 获取之前已经推荐的问题 Ids
            $cacheModel = CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('questions_recommended_read', $uid);

            $oldRecommentIds = $cacheModel->redisHandler->zRange($cacheModel->cacheKey['questions_recommended_read'], 0, -1, false);
        }
        // 剩余推荐问题数
        $num = $limit - count($resIds);

        $num1 = 0;
        $num2 = 0;
        for ($i = 1; $i <= $num; $i++)
        {
            if (ceil($i / 3) % 2 === 0)
            {   // 第五优先级 获取数量
                $num2++;
            } else
            {   // 第四优先级
                $num1++;
            }
        }
        // 获取发布时间距离现在最近3条
        $ids1 = $num1 > 0 ? $this->getQuestionTimeSortIds($uid, $num1, $oldRecommentIds, $excludeIds) : [];
        $allIds = array_merge($excludeIds, $ids1);
        // 获取推荐值最高3条
        $ids2 = $num2 > 0 ? $this->getQuestionRecommendedSortIds($uid, $num2, $oldRecommentIds, $allIds) : [];
        $recommentIds = array_merge($ids1, $ids2);

        for ($i = 1; $i <= $num; $i++)
        {
            if (ceil($i / 3) % 2 === 0)
            {   // 第五优先级取数据
                if ($ids2)
                {
                    $resIds[] = (string)(array_shift($ids2));
                }
            } else
            {   // 第四优先级
                if ($ids1)
                {
                    $resIds[] = (string)(array_shift($ids1));
                }
            }
        }
        $this->setReadIds($uid, $recommentIds);

        return $resIds;
    }

    /**
     * 获取首页展示的 平行宇宙 内容
     * @param int $uid 用户uid
     * @param int $type 1=>默认推荐排序 2=>时间排序
     * @param int $page 当前页数
     * @param int $limit
     * @return array
     * @throws \Exception
     */
    public function getIndexList(int $uid, int $type, int $page, int $limit = 10)
    {
        $pageData = [];
        if ($type === 1)
        {
            $ids = $this->getRecommentQids($uid, $page, $limit);
        } else
        {
            $pageData = $this->getPxyzTimeSortQids($uid, $page, $limit);
            $ids = $pageData['data'];
        }
        $questionListData = $this->batchGetInfoByIds($ids, ['uid', 'status', 'id', 'nickname', 'avatar_id', 'create_time', 'astr_reply_num', 'content', 'imgs', 'comment_num', 'good_num', 'rid1', 'rid2']);
        $auth = 0;  // 0=>用户 1=>占星师
        $goodIds = [];
        if ($uid)
        {   // 判断当前用户身份 是否是占星师
            $userBindAstrInfo = (new ZyhsAstrBindUser())->getAstrBindUserData();
            $auth = isset($userBindAstrInfo[$uid]) ? 1 : 0;
            $goodIds = (new ZyhsArticleGood())->getUserGoodAids($uid, 1);
        }
        // 取 黑名单用户uid   ----------------------------------------------------------------
        // 获取黑名单用户uid
        $blacklistUids = (new ZyhsBlacklist())->getBlackUids(1, $uid);
        $userInfoList = [];
        $userRecodeList = [];
        $listData = [];
        $avatarNicknameConfig = config('pxyz');
        $zyhsArticleCommentModel = new ZyhsArticleComment();
        $zyhsRecodeModel = new ZyhsRecode();
        $utilModel = new Util();
        $zyhsUserModel = new ZyhsUser();
        foreach ($ids as $idItem)
        {
            if (!isset($questionListData[$idItem])) continue;
            $listDatum = $questionListData[$idItem];
            if ($listDatum['status'] !== 1)
            {   // 状态异常 不显示
                continue;
            }
            if (in_array($listDatum['uid'], $blacklistUids, true))
            {
                continue;
            }
            $userDes = '宇宙神秘人';
            if (isset($userRecodeList[$listDatum['uid']]))
            {
                $userDes = $userRecodeList[$listDatum['uid']]['user_des'];
            } else
            {
                $recode = $zyhsRecodeModel->getRecodeLists($listDatum['uid'], 1);
                if ($recode)
                {
                    $userDes = '日' . $utilModel->recodeAstroShorthand($recode['sun']) . '月' . $utilModel->recodeAstroShorthand($recode['moon']) . '升' . $utilModel->recodeAstroShorthand($recode['asc']);
                }
                $userRecodeList[$listDatum['uid']] = [
                    'user_des' => $userDes,
                ];
            }

            $commentIds = $zyhsArticleCommentModel->getContentRecommendedSortIds(1, $idItem, 3);
            $commentList = $commentIds ? $zyhsArticleCommentModel->batchGetInfoByIds($commentIds, ['uid', 'content']) : [];
            $replyData = [];
            foreach ($commentIds as $cidItem)
            {
                if (!isset($commentList[$cidItem]))
                {
                    continue;
                }
                $commentItem = $commentList[$cidItem];
                if ($commentItem['uid'] === $listDatum['uid'])
                {
                    $avatar = $avatarNicknameConfig['avatar_list'][$listDatum['avatar_id']];
                } else
                {
                    if (isset($userInfoList[$commentItem['uid']]))
                    {
                        $avatar = $userInfoList[$commentItem['uid']]['avatar'];
                    } else
                    {
                        $userInfo = $zyhsUserModel->getInfoById($commentItem['uid'], ['avatar']);
                        $avatar = $userInfo['avatar'];
                        $userInfoList[$commentItem['uid']] = ['avatar' => $avatar];
                    }
                }
                $replyData[] = [
                    'avatar' => $avatar,
                    'content' => $commentItem['content'],
                ];
            }
            $recodeData = null;
            if ($listDatum['rid1'])
            {
                $recodeData = [
                    'icon' => '/zyhsapp/pxyz/astro_icon.png',
                    'name' => $listDatum['rid2'] ? '双人星盘' : '单人星盘',
                    'target' => 'local',
                    'link' => 'empty',
                ];
                if ($uid === $listDatum['uid'])
                {   // 本人
                    $recodeData['target'] = 'toast';
                    $recodeData['link'] = '仅支持占星师查看星盘';
                } else
                {
                    if (isset($userBindAstrInfo[$uid]))
                    {   // 咨询师
                        $recodeData['link'] = "other_astrolable?atype=1&aid={$listDatum['id']}&rid1={$listDatum['rid1']}&rid2={$listDatum['rid2']}&need_auth=2";
                    }
                }
            }
            $questionItem = [
                'id' => $listDatum['id'],
                'nickname' => $listDatum['nickname'],
                'avatar' => $avatarNicknameConfig['avatar_list'][$listDatum['avatar_id']],
                'create_time' => Util::timeToStr($listDatum['create_time']),
                'user_des' => $userDes,
                'astr_reply_num' => $listDatum['astr_reply_num'],
                'content' => $listDatum['content'],
                'img_list' => $listDatum['imgs'],
                'recode_data' => $recodeData,
                'reply_num' => $listDatum['comment_num'],
                'good_num' => $listDatum['good_num'],
                'reply_data' => $replyData,
                'is_self' => $uid === $listDatum['uid'] ? 1 : 0,
                'is_good' => in_array($listDatum['id'], $goodIds, true) ? 1 : 0, // 是否 点赞
            ];

            $listData[] = $questionItem;
        }

        if ($type === 2)
        {   // 时间排序
            $pageData['data'] = $listData;
            return $pageData;
        }

        if ($page === 1 && $this->totalNum <= $limit)
        {
            return [
                'total' => count($listData),   // 总数
                'per_page' => $limit,   //每页显示数
                'current_page' => $page,    // 当前页数
                'last_page' => 1,    // 总页数
                'auth' => $auth,
                'data' => $listData,
            ];
        } else
        {
            return [
                'total' => 10000,   // 总数
                'per_page' => $limit,   //每页显示数
                'current_page' => $page,    // 当前页数
                'last_page' => 1000,    // 总页数
                'auth' => $auth,
                'data' => $listData,
            ];
        }
    }

    /**
     * 获取后台推荐
     * @param int $uid
     * @param int $limit
     * @param array $excludeIds 排除的IDS
     * @return array
     * @throws \Exception
     */
    public function getAdminRecommentQids(int $uid, int $limit = 2, array $excludeIds = []): array
    {
        $resData = CacheManageZyhs::getInstance()
            ->setCacheConfig($this->cacheModel)
            ->setPage(-1)
            ->getListPageDataIds(function ($isCache = true, $sortType = 'desc')
            {
                try
                {
                    $data = $this->where(['is_recommend' => 1, 'is_hide' => 0, 'status' => 1])->order('create_time desc')->column('create_time', 'id');
                    $resData = [];
                    foreach ($data as $id => $consultTime)
                    {
                        $resData[$id] = ['create_time' => $consultTime];
                    }

                    return $resData;
                }
                catch (\Exception $e)
                {
                    return [];
                }
            }, 'create_time', 0, 'admin_recommended');

        $resDataIds = array_keys($resData['data']);

        if ($uid)
        {
            $cacheModel = CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('admin_recommended_read', $uid);
            $range = $cacheModel->redisHandler->zRange($cacheModel->cacheKey['admin_recommended_read'], 0, -1, false);
        } else
        {
            $range = [];
        }

        $ids = array_diff($resDataIds, $range, $excludeIds);

        if (count($ids) <= $limit)
        {
            $this->setAdminRecommentReadIds($uid, $ids);
        } else
        {
            shuffle($ids);
            $ids = array_slice($ids, 0, $limit);
            $this->setAdminRecommentReadIds($uid, $ids);
        }

        return $ids;
    }

    /**
     * 设置后台推荐 已推
     * @param int $uid
     * @param array $qids
     * @throws \Exception
     */
    public function setAdminRecommentReadIds(int $uid, array $qids)
    {
        if ($uid)
        {
            $cacheModel = CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('admin_recommended_read', $uid);

            $redis = $cacheModel->redisHandler;
            $expire = 0;
            if (!$cacheModel->existsKey('admin_recommended_read'))
            {   // 首次 创建 设置过期时间 7天
                $expire = 604800;
            }

            foreach ($qids as $qid)
            {
                $redis->zAdd($cacheModel->cacheKey['admin_recommended_read'], [], $qid, $qid);
            }

            if ($expire > 0)
            {
                $redis->expire($cacheModel->cacheKey['admin_recommended_read'], $expire);
            }
        }
    }

    public function getPxyzTimeSortQids(int $uid, int $page, int $limit)
    {
        $nowTime = time();
        $excludeId = 0;
        if ($uid)
        {   // 获取 用户 最新发布的一条
            request()->get(['page' => 1]);
            $this->pageLimit = 2;
            $pageData = $this->getListPage($uid, 'create_time', ['create_time', 'status', 'id'], 0, 'desc', 0);
            foreach ($pageData['data'] as $itemInfo)
            {
                if ($nowTime - $itemInfo['create_time'] < 86400 && (int)$itemInfo['status'] === 1)
                {
                    $excludeId = (int)$itemInfo['id'];
                    break;
                }
            }
        }
        // 获取 所有的 内容ID列表
        $resIdsData = $this->getPxyzTimeSortIdsCache();
        if ($excludeId)
        {
            unset($resIdsData['data'][$excludeId]);
            $ids = array_keys($resIdsData['data']);
            array_unshift($ids, $excludeId);
        } else
        {
            $ids = array_keys($resIdsData['data']);
        }

        $resData = getPaginatorData(count($ids), $page, $limit);
        //获取分页后的数据
        $resData['data'] = array_slice($ids, $resData['start'], $limit);
        unset($resData['start']);
        unset($resData['end']);

        return $resData;
    }

    public function getPxyzTimeSortIdsCache()
    {
        $resData = CacheManageZyhs::getInstance()
            ->setCacheConfig($this->cacheModel)
            ->setPage(-1)
            ->setSort('desc')
            ->getListPageDataIds(function ($isCache = true, $sortType = 'desc')
            {
                try
                {
                    $data = $this->where(['status' => 1, 'is_hide' => 0])->order('create_time ' . $sortType)->column('create_time', 'id');
                    $resData = [];
                    foreach ($data as $id => $createTime)
                    {
                        $resData[$id] = ['create_time' => $createTime];
                    }

                    return $resData;
                }
                catch (\Exception $e)
                {
                    return [];
                }
            }, 'create_time', 0, 'time_sort');

        return $resData;
    }

    /**
     * 获取 平行宇宙 首页 时间排序
     * @param int $uid
     * @param int $limit
     * @param array $excludeIds1 排除 之前已推荐
     * @param array $excludeIds2 排除 本次推荐
     * @return array|mixed
     * @throws \Exception
     */
    public function getQuestionTimeSortIds(int $uid, int $limit, array $excludeIds1 = [], array $excludeIds2 = [])
    {
        $resData = $this->getPxyzTimeSortIdsCache();

        $resDataIds = array_keys($resData['data']);
        $this->totalNum = count($resDataIds);
        $ids = array_diff($resDataIds, $excludeIds1, $excludeIds2);

        $num = count($ids);

        if ($num < $limit)
        {
            $endNum = $limit - $num;

            $ids2 = array_diff($resDataIds, $ids, $excludeIds2);
            // 删除已经推荐的记录
            $this->delReadIdsCacheData($uid);
            if (count($ids2) <= $endNum)
            {
                return array_merge($ids, $ids2);
            } else
            {
                $ids3 = array_slice($ids2, 0, $endNum);
                return array_merge($ids, $ids3);
            }
        } elseif ($num === $limit)
        {
            return $ids;
        } else
        {
            return array_slice($ids, 0, $limit);
        }
    }

    /**
     * 获取 平行宇宙 首页 推荐值排序
     * @param $uid
     * @param int $limit
     * @param array $excludeIds1 排除 之前已推荐
     * @param array $excludeIds2 排除 本次推荐
     * @return array|mixed
     * @throws \Exception
     */
    public function getQuestionRecommendedSortIds($uid, int $limit, array $excludeIds1 = [], array $excludeIds2 = [])
    {
        $nowTime = time();
        $resData = CacheManageZyhs::getInstance()
            ->setCacheConfig($this->cacheModel)
            ->setPage(-1)
            ->getListPageDataIds(function ($isCache = true, $sortType = 'desc') use ($nowTime)
            {
                try
                {
                    $data = $this->where(['status' => 1, 'is_hide' => 0])->column('create_time,comment_num,good_num', 'id');
                    $rData = [];
                    foreach ($data as $id => $questionItem)
                    {
                        // $recommendedNum = $questionItem['comment_num'] * 5 + $questionItem['same_num'] * 3 + $questionItem['read_num'] * 2;
                        $recommendedNum = $questionItem['comment_num'] + $questionItem['good_num'];
                        $timeLong = $nowTime - $questionItem['create_time'];
                        switch (true)
                        {
                            case $timeLong < 604800: // 86400*7
                                $recommendedNum = $recommendedNum / 1;
                                break;
                            case $timeLong < 1296000: // 86400*15
                                $recommendedNum = $recommendedNum / 2;
                                break;
                            case $timeLong < 2592000:// 86400*30
                                $recommendedNum = $recommendedNum / 5;
                                break;
                            case $timeLong >= 2592000:// 86400*30
                                $recommendedNum = $recommendedNum / 10;
                                break;
                            default:
                                $recommendedNum = 0;
                        }
                        $rData[$id] = $recommendedNum + ($id / 100000000);
                        // $rData[$id] = "{$recommendedNum}.{$id}";
                    }

                    if ($rData)
                    {
                        arsort($rData);
                    }
                    $resData = [];
                    foreach ($rData as $id => $resDatum)
                    {
                        $resData[$id] = ['recommended_num' => $resDatum];
                    }

                    return $resData;
                }
                catch (\Exception $e)
                {
                    return [];
                }
            }, 'recommended_num', 0, 'recommended_sort');

        $resDataIds = array_keys($resData['data']);
        $ids = array_diff($resDataIds, $excludeIds1, $excludeIds2);
        $num = count($ids);

        if ($num < $limit)
        {
            $endNum = $limit - $num;
            $ids2 = array_diff($resDataIds, $ids, $excludeIds2);
            // 删除已经推荐的记录
            $this->delReadIdsCacheData($uid);
            if (count($ids2) <= $endNum)
            {
                return array_merge($ids, $ids2);
            } else
            {
                $ids3 = array_slice($ids2, 0, $endNum);
                return array_merge($ids, $ids3);
            }
        } elseif ($num === $limit)
        {
            return $ids;
        } else
        {
            return array_slice($ids, 0, $limit);
        }
    }

    /**
     * 删除 平行宇宙 已推 的缓存
     */
    public function delReadIdsCacheData(int $uid)
    {
        if ($uid && !$this->isDelUserReadQuestionRecord)
        {
            $this->isDelUserReadQuestionRecord = true;
            CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('questions_recommended_read', $uid)->rmCache('questions_recommended_read');
        }
    }

    /**
     * 设置 平行宇宙 推荐 已推
     * @param int $uid
     * @param array $qids
     * @throws \Exception
     */
    public function setReadIds(int $uid, array $qids)
    {
        if ($uid)
        {
            $cacheModel = CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('questions_recommended_read', $uid);

            $redis = $cacheModel->redisHandler;
            $expire = 0;
            if (!$cacheModel->existsKey('questions_recommended_read'))
            {   // 首次 创建 设置过期时间 7天
                $expire = 604800;
            }

            foreach ($qids as $qid)
            {
                $redis->zAdd($cacheModel->cacheKey['questions_recommended_read'], [], $qid, $qid);
            }

            if ($expire > 0)
            {
                $redis->expire($cacheModel->cacheKey['questions_recommended_read'], $expire);
            }
        }
    }

    /**
     * 重写数据时获取数据
     * @param $ids
     * @param $type
     * @param $sortType
     * @return array|false|string
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            if ($ids)
            {
                $model = $this->where('id', 'in', $ids);
            } else
            {
                $model = $this->where(['uid' => $type[0], 'status' => 1]);
            }

            $data = $model
                ->order('create_time', 'DESC')
                ->column('id,uid,is_top,is_recommend,avatar_id,nickname,is_hide,status,content,imgs,rid1,rid2,recode_data,read_num,comment_num,good_num,astr_reply_num,create_time', 'id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }

        return $data;
    }

    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        return $this->dataInit($resData);
    }

    public function dataInit(array $resData): array
    {
        foreach ($resData as $orderId => $questionItemData)
        {
            $resData[$orderId] = arrayKeyData2int($questionItemData, ['id', 'status', 'uid', 'is_top', 'is_recommend', 'avatar_id', 'is_hide', 'rid1', 'rid2', 'read_num', 'comment_num', 'good_num', 'astr_reply_num', 'create_time']);
            if (isset($questionItemData['imgs']))
            {
                $resData[$orderId]['imgs'] = $questionItemData['imgs'] ? json_decode($questionItemData['imgs'], true) : [];
            }
            if (isset($questionItemData['recode_data']))
            {
                $resData[$orderId]['recode_data'] = $questionItemData['recode_data'] ? json_decode($questionItemData['recode_data'], true) : [];
            }
        }
        return $resData;
    }

    /**
     * @param $aid
     * @param string $cacheKey good_num | comment_num | read_num
     * @param array $data ['good_num' =>0,'comment_num' =>0,'read_num' =>0,'astr_reply_num'=>0]  // 占星师 发布1及评论时 astr_reply_num 字段存在
     * @param int $inc
     * @return void
     * @throws \Exception
     */
    public function updateCommentNumData($aid, string $cacheKey, array $data, int $inc = 1): void
    {
        $cache = CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $aid);
        $data[$cacheKey] = $data[$cacheKey] + $inc;
        if ($inc < 0 && $data[$cacheKey] < 0)
        {
            $data[$cacheKey] = 0;
            $cache->setCache($data);
        } else
        {   // 更新 缓存
            if (isset($data['astr_reply_num']))
            {
                $cache->setCache($data);
            } else
            {
                $cache->setCacheInc($cacheKey, 'details', $inc);
            }
        }
        // 基数记录增加   用于减少更新数据库频率
        $addNum = $cache->setCacheKeyDetail('inc_base_num', $aid)->setCacheInc($cacheKey, 'inc_base_num', 1);
        if ($addNum > ($cache->cacheKey['base_max'] ?? 5) || isset($data['astr_reply_num']))    // 咨询师 回复时 必须更新
        {   // 删除记录
            $cache->rmCache('inc_base_num');
            // 更新 入库
            $this->where(['id' => $aid])->update($data);
        }
    }

    /**
     * 获取 我的发布 数据信息
     * @param int $uid
     * @param int $page
     * @param int $limit
     * @return array
     * @throws \Exception
     */
    public function getMyPublishData(int $uid, int $page, int $limit = 10)
    {
        $resData = CacheManageZyhs::getInstance()
            ->setCacheConfig($this->cacheModel, $uid)
            ->setPage($page)
            ->setPageSize($limit)
            ->setSort('desc')
            ->setListKeyType(0)
            ->getListPageDataIds(function ($isCache = true, $sortType = 'desc') use ($uid)
            {
                try
                {
                    $data = $this->where(['uid' => $uid, 'status' => 1])->order('create_time desc')->column('create_time', 'id');
                    $resData = [];
                    foreach ($data as $id => $createTime)
                    {
                        $resData[$id] = ['create_time' => $createTime];
                    }

                    return $resData;
                }
                catch (\Exception $e)
                {
                    return [];
                }
            }, 'create_time', 0);
        if (empty($resData['data']))
        {
            return $resData;
        }
        $ids = array_keys($resData['data']);
        $contentList = $this->batchGetInfoByIds($ids, ['content', 'create_time', 'astr_reply_num', 'good_num', 'comment_num']);
        $data = [];
        foreach ($resData['data'] as $idItem => $datum)
        {
            if (!isset($contentList[$idItem]))
            {
                continue;
            }
            $dataItem = $contentList[$idItem];
            // $desc = '3咨询师 · 19评论 · 132鼓励 | 暂无互动';
            $desc = '';
            if ($dataItem['astr_reply_num'])
            {
                $desc .= (empty($desc) ? '' : ' · ') . "{$dataItem['astr_reply_num']}咨询师";
            }
            if ($dataItem['comment_num'])
            {
                $desc .= (empty($desc) ? '' : ' · ') . "{$dataItem['comment_num']}评论";
            }
            if ($dataItem['good_num'])
            {
                $desc .= (empty($desc) ? '' : ' · ') . "{$dataItem['good_num']}鼓励";
            }
            $data[] = [
                'title' => $dataItem['content'],
                'des' => $desc ?: '暂无互动',
                'create_time' => Util::timeToStr($dataItem['create_time']),
                'id' => $idItem,
                'target' => 'local',
                'link' => "community_detail?id={$idItem}&need_auth=2",
            ];
        }
        $resData['data'] = $data;
        return $resData;
    }
}